package com.gyh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gyh.entity.Course;
import com.gyh.entity.Member;
import com.gyh.service.CoachService;
import com.gyh.service.CourseService;
import com.gyh.service.MemberService;
import com.gyh.service.ReserveService;
import com.gyh.util.JWTUtil;
import com.gyh.util.Result;
import com.gyh.vo.CourseVo;
import io.jsonwebtoken.Claims;
import org.apache.el.parser.Token;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {
    @Resource
    private CourseService courseService;
    @Resource
    private MemberService memberService;
    @Resource
    private ReserveService reserveService;
    @GetMapping
    public Result getAll(){
        List<Course> courses = courseService.getAll();
        return Result.success(null,courses);
    }
    @GetMapping("/getComprehensiveCourses")
    public Result getComprehensiveCourses(){
        List<Course> courses = courseService.getComprehensiveCourses();
        return Result.success(null,courses);
    }
    @GetMapping("/getLatestCourses")
    public Result getLatestCourses(){
        List<Course> courses = courseService.getLatestCourses();
        return Result.success(null,courses);
    }
    @GetMapping("/getPopularCourses")
    public Result getPopularCourses(){
        List<Course> courses = courseService.getPopularCourses();
        return Result.success(null,courses);
    }
    @GetMapping("/getCourse")
    public Result getCourse(Integer id){
        CourseVo course = courseService.getCourseById(id);
        return Result.success(null,course);
    }
    @GetMapping("/getMyCourses")
    public Result getMyCourses(HttpServletRequest request){
        String token = request.getHeader("token");
        String phone = null;
        try {
            Claims claims = JWTUtil.parseJWT(token);
            phone = claims.getSubject();
        } catch (Exception e) {
           return Result.error(401,"未登录");
        }QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        Member member = memberService.getOne(queryWrapper);
        List<Integer> cids = reserveService.getCidByMid(member.getId());
        List<Course> courses = new ArrayList<>();
        Course course = null;
        for (Integer cid : cids) {
            course = courseService.getCourseById(cid);
            courses.add(course);
        }
        return Result.success(null,courses);
    }
}
